const express = require('express')
const { query } = require('../db')
const router = express.Router()

// 评论列表
router.get('/list', async (req,res,next) => {
  const page = 10
  // 获取get传递的参数
  let { pno,name } = req.query
  console.log(pno)
  let str = ''
  if(name) {
    // 如果传递的姓名有值
    str = `&& c.name like '%${name}%'`
  }
  if(!pno) {
    pno = 1
  }
  let start = (pno - 1) * page
  // 执行SQL命令
  try {
    var data = await query(`select a.id,b.num,c.name,c.avatar,a.star,a.user,a.content,a.ctime from hs_comment a,hs_order b,hs_expert c where a.order_id=b.id && a.expert_id=c.id ${str} order by id desc limit ${start},${page};select count(*) n from hs_comment a,hs_order b,hs_expert c where a.order_id=b.id && a.expert_id=c.id ${str}`)
  } catch(err) {
    return next(err)
  }
  console.log(data)

  res.send({
    code: 200,
    msg: '评论列表',
    data: data[0],
    total: data[1][0].n,
    pno
  })
})
// 删除评论
router.delete('/',async (req,res,next) => {
  // 获取get传递的参数
  const {id} = req.query
  if(!id) {
    return res.send({
      code: 401,
      msg: 'id不能为空'
    })
  }
  // 执行SQL命令
  try {
    var data = await query('delete from hs_comment where id=?',[id])
  } catch(err) {
    return next(err)
  }
  if(data.affectedRows === 0) {
    res.send({
      code: 410,
      msg: '评论删除失败'
    })
  } else {
    res.send({
      code: 200,
      msg: '评论删除成功'
    })
  }
})

module.exports = router